<html>
<head>
<title>Original Title</title>
<link rel="shortcut icon" type="image/x-icon" href="http://test.com/oldfavicon.ico"/>
<link rel="shortcut icon" type="image/x-icon" href="http://test.com/foofavicon.ico"/>
<link rel="shortcut icon" type="image/x-icon" href="http://test.com/barfavicon.ico"/>
<link rel="shortcut icon" type="image/x-icon" href="http://test.com/darkfavicon.ico" media="(prefers-color-scheme: dark)"/>
<link rel="shortcut icon" type="image/x-icon" href="http://test.com/lightfavicon.ico" media="(prefers-color-scheme: light)"/>
<script src="../../resources/js-test.js"></script>
<script>

function setFavIcon(iconURL) {
    var docHead = document.getElementsByTagName("head")[0];

    // set up a new node for the new iconURL
    var newLink = document.createElement("link");
    newLink.type = "image/x-icon";
    newLink.rel = "shortcut icon";
    newLink.href = iconURL;

    var links = docHead.getElementsByTagName("link");
    for (var i = 0; i < links.length; ++i) {
        var oldLink = links[i];
        if (oldLink.type=="image/x-icon" && oldLink.rel=="shortcut icon") {
          // if we find the child, replace it with the new node.
          docHead.replaceChild(newLink, oldLink);
          return; // Assuming only one match at most.
        }
    }

    // if we didn't find the icon URL link, add it now.
    docHead.appendChild(newLink);
}

function runTests() {
    if (window.testRunner)
        testRunner.dumpAsText();

    iconURL = document.getElementsByTagName("link")[0].href;
    debug('Original iconURL is: ' + iconURL);

    // change icon to new icon
    newURL = 'http://test.com/newfavicon.ico';
    debug('Setting new icon URL to: ' + newURL);
    setFavIcon(newURL);
    iconURL = document.getElementsByTagName("link")[0].href
    debug('New iconURL is: ' + iconURL);

    // check that the URL list in the document is as we expect
    var expectedURL0 = "http://test.com/lightfavicon.ico";
    var expectedURL1 = "http://test.com/barfavicon.ico";
    var expectedURL2 = "http://test.com/foofavicon.ico";
    var expectedURL3 = "http://test.com/newfavicon.ico";
    var iconURLs = internals.shortcutIconURLs(document);
    if (expectedURL0 == iconURLs[0] && expectedURL1 == iconURLs[1] && expectedURL2 == iconURLs[2] && expectedURL3 == iconURLs[3])
        testPassed('URL list matches expected');
    else
        testFailed('URL list does not match expected');
}

</script>
</head>
<body onload='runTests();'>
</div>
</body>
</html>
